#include "main.h"
int writeToArc ( FILE * arc, FILE * fileToRead, fileHead * fileHd)
{
	unsigned int CheckSum = 0;
	unsigned long long int count = 0;
	char * buf = (char*) calloc (SIZE_BUF,sizeof(char));
	int rc = 0;
	unsigned int sizeFileSz = 0;
	if (!buf)	cl_exit (WRITE_TO_ARC,MEMORY_ERR);
	intWrite (arc,(unsigned long long int) fileHd->sizeName,NAME_LEN,&CheckSum);
	strWrite (arc,fileHd->fileName,fileHd->sizeName,&CheckSum);
	intWrite (arc, fileHd -> mtime, SIZE_T_8, &CheckSum);
	if (fileHd->huff_ubits & NO_HUFF)	{
		intWrite (arc,(unsigned long long int) fileHd->huff_ubits, SIZE_T_1,&CheckSum);
		if (fileHd->huff_ubits & LEN_8_B )	{	
			intWrite (arc, fileHd->fileSize, SIZE_T_8, &CheckSum);
			sizeFileSz = SIZE_T_8;
		}
		else {
			intWrite (arc, fileHd->fileSize, 4, &CheckSum);
			sizeFileSz = SIZE_T_4;
		}
	}
	else	{
		fileToRead = compres (fileToRead,fileHd);
		fseek (fileToRead,0,SEEK_SET);
		intWrite (arc,(unsigned long long int) fileHd->huff_ubits, SIZE_T_1,&CheckSum);
		if (fileHd->huff_ubits & LEN_8_B )	{	
			intWrite (arc, fileHd->fileSize, SIZE_T_8, &CheckSum);	
			sizeFileSz = SIZE_T_8;
			intWrite (arc,(unsigned long long int) fileHd->huff_block, SIZE_T_2, &CheckSum);
			intWrite (arc,fileHd->huff_file_len, SIZE_T_8, &CheckSum);
		}
		else {
			intWrite (arc, fileHd->fileSize, SIZE_T_4, &CheckSum);
			sizeFileSz = SIZE_T_4;
			intWrite (arc,(unsigned long long int) fileHd->huff_block, SIZE_T_2, &CheckSum);
			intWrite (arc,fileHd->huff_file_len, SIZE_T_4, &CheckSum);
		}	
	}
	for (;;)	{
		if ((rc = fread (buf,sizeof(char),SIZE_BUF,fileToRead)) == SIZE_BUF)	{	
			count += rc;	
			strWrite (arc,buf,SIZE_BUF,&CheckSum);	
		}
		else {
			if (rc!= 0)	strWrite (arc,buf,rc,&CheckSum);	
			count += rc;
			break;	
		}
	}
#ifdef __DEBUG_
	printf ("old %u\n", CheckSum);
#endif
	intWrite (arc,CheckSum,4,&CheckSum);
	return 0;
}
